package com.swu.pad.course.service.impl;

import java.util.Date;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.swu.pad.course.dao.CourseGroupUserDao;
import com.swu.pad.course.entity.CourseGroupUser;
import com.swu.pad.course.service.CourseGroupUserService;
import com.swu.pad.util.StringUtil;
import com.swu.pad.util.EPLiteClient.EPLiteClient;

@Service
@Transactional
public class CourseGroupUserServiceImpl implements CourseGroupUserService {

	@Autowired
	private CourseGroupUserDao courseGroupUserDao;
	@Autowired
	private EPLiteClient epliteClient;

	public CourseGroupUser addCourseGroupUser(CourseGroupUser courseGroupUser) {
		CourseGroupUser temp = courseGroupUserDao.findCourseGroupUserByGroupIdAndUserId(courseGroupUser.getGroupId(), courseGroupUser.getUserId());
		if (!StringUtil.isValid(courseGroupUser.getId()) && temp == null) {
			Map<?, ?> sessionMap = epliteClient.createSession(courseGroupUser.getGroupId(), courseGroupUser.getUserId(), new Date().getTime());
			String sessionId = sessionMap.get("sessionID").toString();
			courseGroupUser.setId(sessionId);
		} else {
			courseGroupUser.setId(temp.getId());
		}
		return courseGroupUserDao.save(courseGroupUser);
	}

	@Transactional(rollbackFor = Exception.class)
	public void deleteCourseGroupUser(String courseGroupUserId) {
		// 删除courseGroupUser（etherpad中的session）
		CourseGroupUser courseGroupUser = courseGroupUserDao.findOne(courseGroupUserId);
		epliteClient.deleteSession(courseGroupUser.getId());
		courseGroupUserDao.delete(courseGroupUser);
	}

}
